<?php 
if (!defined('BASEPATH')) exit('No direct access allowed.'); 

class MY_Controller extends CI_Controller {

	protected $ci;
	public $user_id;
	
    public function __construct() { 
        parent::__construct();
		
		$this->load->database();
		$this->load->helper('url');
		
		$this->load->helper('Functions');
		
		$this->user_id = 0;
		$this->CheckLogin();
    } 


    public function out($data=array()) {
       $arr = array('result_code'=>0,'message'=>'','data'=>'');
	   
	   foreach($data as $key=>$val){
		   $arr[$key] = $val;
	   }
	   echo json_encode($arr);
	   exit;
    }
	
	public function data_out($data=array(),$message="获取数据成功"){
		
		$arr = array('result_code'=>0,'message'=>$message,'data'=>$data);
	    $this->out($arr);
	}
	public function err_out($message,$result_code=1) {
       $arr = array('result_code'=>$result_code,'message'=>$message);
	   $this->out($arr);
    }
	
	function CheckLogin(){		

		//$token = 'Umg3dWJmcDdwYnVPYVpKd3JSZVM5Z3E0MWY2T0hjTWdOZ2NXaVlGMno=';//$this->input->post('token');
		$token = $this->input->post('token',null,'');
		if(empty($token)){
			$this->err_out('token错误',401);	
		}
		
		$this->load->model("User/CoachModel",'Coach');	
		$openid = $this->Coach->token_get_openid($token);
		
		if(empty($openid)){
			$this->err_out('token错误',401);	
		}
		
		//$openid = 'oKegA5RsEIkjckYEK9RZl3x0Cfm0';
		$row = $this->Coach->openid_getinfo($openid);
		
		if(!$row){
			$this->err_out('token错误',401);			
		}
		
		$this->user_id = $row['id'];
		$this->shop_id = $row['shop_id'];
		
		$this->_user = $row;
	}
	
	function CheckData($arr=array(),$data=array()){
		//验证参数
		$this->load->library('form_validation');
		
		$config = array();
		
		foreach($arr as $key=>$val){
			$msg = "";
			if(is_array($val)){
				$msg = $val[key($val)];
				$rules = key($val);
			}
			else{
				$msg = $val;
				$rules = 'required';
			}
			
			$config[] = array(
					'field' => $key,
					'label' => $key,
					'rules' => $rules,
					'errors' => array(
						$rules => $msg,
					),
				);
		}


		$this->form_validation->set_data($data);
		$this->form_validation->set_rules($config);

		if($this->form_validation->run() === FALSE){
			$err_arr = $this->form_validation->error_array();
			
			return implode("\n",$err_arr);
        }
		return false;
	}
	
	
} 